package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.MineYiYuanAdapter;
import com.xn.app.muying.bean.MineYiYuanBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 医院选择
 * Created by Administrator on 2016/10/19.
 */
public class JiuZhenActivity extends BaseActivity implements HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener {
    private Handler handler = new Handler();
    private ListView lv;
    private MineYiYuanAdapter adapter;
    private ImageView yunqixuanze_activity_back;
    ArrayList<MineYiYuanBean> list;
    //标题
    private TextView title = null;
    //数据显示页面
    private LinearLayout linearlayout = null;
    //无数据显示页面
    private LinearLayout no_data_linearlayout = null;
    //无数据显示数据
    private TextView no_data_textview = null;
    //数据库
    private DBManager db = null;
    //加载框
    AlertDialog dialog;
    //获取页面传来的值
    private String sign = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jiuzhen);
        db = new DBManager(this);
        lv = (ListView) findViewById(R.id.jiuzhen_activity_lv);
        yunqixuanze_activity_back = (ImageView) findViewById(R.id.yunqixuanze_activity_back);
        linearlayout = (LinearLayout) findViewById(R.id.linearlayout);
        title = (TextView) findViewById(R.id.title);
        no_data_linearlayout = (LinearLayout) findViewById(R.id.no_data_linearlayout);
        no_data_textview = (TextView) findViewById(R.id.no_data_textview);
        //设置标题
        sign = getIntent().getStringExtra("SIGN");
        if (sign != null && sign.equals("NO_SAVE_PREGNANCY")) {
            title.setText("选择医院");
        } else if (sign != null && sign.equals("introduction")) {
            title.setText("选择医院");
        } else {
            title.setText("就诊医院");
        }
        yunqixuanze_activity_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        adapter = new MineYiYuanAdapter(this);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
        if (NetworkUtil.isNetworkAvailable(JiuZhenActivity.this)) {
            dialog = new MyAlertDialog().ShowDialog(JiuZhenActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            HttpUtil.getData(APIMethod.Mine_JiuZhenYiYuan, handler, this);
        } else {
            no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
            no_data_textview.setText(R.string.no_network_hint);
        }
    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.optString("name");
                int id = object.optInt("id");
                String address = object.optString("address");
                MineYiYuanBean bean = new MineYiYuanBean();
                bean.setName(name);
                bean.setId(id);
                bean.setAddress(address);
                list.add(bean);
            }
            if (list.size() > 0) {
                adapter.getData(list);
                linearlayout.setVisibility(LinearLayout.VISIBLE);
                no_data_linearlayout.setVisibility(LinearLayout.GONE);
            } else {
                linearlayout.setVisibility(LinearLayout.GONE);
                no_data_linearlayout.setVisibility(LinearLayout.VISIBLE);
                no_data_textview.setText("暂无医院信息");
            }
            if (dialog != null) {
                dialog.dismiss();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent intent = new Intent();
        intent.putExtra("HOSPTIALNAME", list.get(i).getName());
        intent.putExtra("HOSPTIALID", list.get(i).getId());
        if (sign != null) {
            //孕期设置
            if (sign.equals("continue")) {
                String pageIntent = getIntent().getStringExtra("PAGE_INTENT");
                if (pageIntent != null) {
                    intent.putExtra("PAGE_INTENT", pageIntent);
                    intent.setClass(this, YunChanSheZhiActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(this, "设置失败", Toast.LENGTH_SHORT).show();
                }
            } else if (sign.equals("NO_SAVE_PREGNANCY")) {
                //孕期检查
                intent.setClass(this, ChanJianListActivity.class);
                startActivity(intent);
                finish();
            } else if (sign.equals("introduction")) {
                //医生介绍
                intent.setClass(this, DoctorActivity.class);
                intent.putExtra("id", list.get(i).getId());
                intent.putExtra("name", list.get(i).getName());
                startActivity(intent);
            } else {
                //选择就诊医院
                updateInterfaceData(list.get(i).getId(), list.get(i).getName());
            }

        } else {
            Toast.makeText(this, "设置失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void updateInterfaceData(final int id, final String name) {
        dialog = new MyAlertDialog().ShowDialog(JiuZhenActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HashMap<String, Integer> param = new HashMap<>();
                    param.put("antenatalCareHospitalId", id);
                    String p = new Gson().toJson(param);
                    RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), p);
                    Request request = new Request.Builder().url(APIMethod.JiuZhenHospital_Sumit).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).put(formBody).build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    if (code == 204 || code == 200) {
                        Message msg2 = new Message();
                        msg2.what = 0;
                        msg2.obj = id + ":" + name;
                        handler1.sendMessage(msg2);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.arg1 = code;
                        msg1.obj = "";
                        handler1.sendMessage(msg1);
                    }


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (dialog != null) {
                dialog.dismiss();
            }
            switch (msg.what) {
                case 0:
                    String str[] = msg.obj.toString().split(":");
                    ToastUtil.showToast(JiuZhenActivity.this, "医院选择成功");
                    db.updateUserHospital(str[0], str[1], db.select("tel"));
                    sendBroadcast(new Intent("bei_er").putExtra("bei_er", 0));
                    //如果是选择宝宝出生进入的选择医院界面，那么选择医院后，直接跳转到下级页面
                    if (sign.equals("baby")) {
                        startActivity(new Intent(JiuZhenActivity.this, BabyActivity.class));
                    }
                    //如果是选择胎心监护进入的选择医院界面，那么选择医院后，直接跳转到下级页面
                    if (sign.equals("MonitorSelect")) {
                        startActivity(new Intent(JiuZhenActivity.this, MonitorSelectActivity.class));
                    }

                    finish();
                    break;
                case 1:
                    ToastUtil.showToast(JiuZhenActivity.this, "医院选择失败");
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
    }
}
